﻿using Microsoft.AspNetCore.Mvc;
using RBAC_Application.Dto.Input;
using RBAC_Application.Dto.Output;
using RBAC_Application.Dto.批量分配;
using RBAC_Application.Repository.Interface;
using RBAC_Application.Service.RBAC;
using Standard;

namespace B.MES.Login.Controllers
{
    /// <summary>
    /// 权限管理
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class PermissionController : ControllerBase
    {
        private readonly IRbacService _rbacService;

        public PermissionController(IRbacService rbacService)
        {
            _rbacService = rbacService;
        }

        /// <summary>
        /// 权限列表查询
        /// </summary>
        [HttpGet]
        public ApiResult<List<PermissionDto>> GetPermissions([FromQuery] string keyword = null, [FromQuery] string module = null)
        {
            try
            {
                var permissions = _rbacService.GetPermissionsByCondition(keyword, module);
                return new ApiResult<List<PermissionDto>>
                {
                    Code = ApiCode.Success,
                    ResultData = permissions,
                    Message = "获取成功"
                };
            }
            catch (Exception ex)
            {
                return new ApiResult<List<PermissionDto>>
                {
                    Code = ApiCode.InternalError,
                    Message = ex.Message
                };
            }
        }

        /// <summary>
        /// 创建权限
        /// </summary>
        [HttpPost]
        public ApiResult<int> CreatePermission([FromBody] CreatePermissionInput input)
        {
            try
            {
                _rbacService.CreatePermission(input);
                return new ApiResult<int>
                {
                    Code = ApiCode.Success,
                    ResultData = 1,
                    Message = "创建成功"
                };
            }
            catch (Exception ex)
            {
                return new ApiResult<int>
                {
                    Code = ApiCode.InternalError,
                    Message = ex.Message
                };
            }
        }

        /// <summary>
        /// 更新权限
        /// </summary>
        [HttpPut]
        public ApiResult<int> UpdatePermission([FromBody] UpdatePermissionInput input)
        {
            try
            {
                _rbacService.UpdatePermission(input);
                return new ApiResult<int>
                {
                    Code = ApiCode.Success,
                    ResultData = 1,
                    Message = "更新成功"
                };
            }
            catch (Exception ex)
            {
                return new ApiResult<int>
                {
                    Code = ApiCode.InternalError,
                    Message = ex.Message
                };
            }
        }

        /// <summary>
        /// 删除权限
        /// </summary>
        [HttpDelete("{id}")]
        public ApiResult<int> DeletePermission(long id)
        {
            try
            {
                _rbacService.DeletePermission(id);
                return new ApiResult<int>
                {
                    Code = ApiCode.Success,
                    ResultData = 1,
                    Message = "删除成功"
                };
            }
            catch (Exception ex)
            {
                return new ApiResult<int>
                {
                    Code = ApiCode.InternalError,
                    Message = ex.Message
                };
            }
        }

        /// <summary>
        /// 检查权限名唯一性
        /// </summary>
        [HttpGet("exists")]
        public ApiResult<bool> CheckPermissionNameExists([FromQuery] string permissionName)
        {
            try
            {
                var exists = _rbacService.CheckPermissionNameExists(permissionName);
                return new ApiResult<bool>
                {
                    Code = ApiCode.Success,
                    ResultData = exists,
                    Message = exists ? "权限名已存在" : "权限名可用"
                };
            }
            catch (Exception ex)
            {
                return new ApiResult<bool>
                {
                    Code = ApiCode.InternalError,
                    Message = ex.Message
                };
            }
        }

        ///<summary>
        /// 获取权限树结构
        /// </summary>
        /// <returns>权限树结构列表</returns>
        [HttpGet("tree")]
        public ApiResult<List<PermissionTreeNode>> GetPermissionTree()
        {
            try
            {
                var tree = _rbacService.GetPermissionTree();
                return new ApiResult<List<PermissionTreeNode>>
                {
                    Code = ApiCode.Success,
                    ResultData = tree,
                    Message = "获取成功"
                };
            }
            catch (Exception ex)
            {
                return new ApiResult<List<PermissionTreeNode>>
                {
                    Code = ApiCode.InternalError,
                    Message = ex.Message
                };
            }
        }

        /// <summary>
        /// 批量分配角色权限
        /// </summary>
        /// <param name="roleId">id</param>
        /// <param name="permissionIds">批量id</param>
        [HttpPost("assign-batch")]
        public ApiResult<int> AssignRolePermissionsBatch([FromBody] RolePermissionBatchInput input)
        {
            try
            {
                _rbacService.AssignRolePermissionsBatch(input.RoleId, input.PermissionIds);
                return new ApiResult<int> { Code = ApiCode.Success, ResultData = 1, Message = "批量分配成功" };
            }
            catch (Exception ex)
            {
                return new ApiResult<int> { Code = ApiCode.InternalError, Message = ex.Message };
            }
        }
        /// <summary>
        /// 批量移除角色权限
        /// </summary>
        /// <param name="roleId">id</param>
        /// <param name="permissionIds">批量id</param>
        [HttpPost("remove-batch")]
        public ApiResult<int> RemoveRolePermissionsBatch([FromBody] RolePermissionBatchInput input)
        {
            try
            {
                _rbacService.RemoveRolePermissionsBatch(input.RoleId, input.PermissionIds);
                return new ApiResult<int> { Code = ApiCode.Success, ResultData = 1, Message = "批量移除成功" };
            }
            catch (Exception ex)
            {
                return new ApiResult<int> { Code = ApiCode.InternalError, Message = ex.Message };
            }
        }
        /// <summary>
        /// 获取用户权限
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        [HttpGet("user-permissions")]
        public ApiResult<List<PermissionDto>> GetUserResourcePermissions([FromQuery] long userId)
        {
            try
            {
                var permissions = _rbacService.GetUserPermissions(userId);
                // 只返回资源相关字段
                var resourcePermissions = permissions
                    .Where(p => !string.IsNullOrEmpty(p.ResourceType) && !string.IsNullOrEmpty(p.ResourceKey))
                    .Select(p => new PermissionDto
                    {
                        ResourceType = p.ResourceType,
                        ResourceKey = p.ResourceKey
                    }).ToList();

                return new ApiResult<List<PermissionDto>>
                {
                    Code = ApiCode.Success,
                    ResultData = resourcePermissions,
                    Message = "获取成功"
                };
            }
            catch (Exception ex)
            {
                return new ApiResult<List<PermissionDto>>
                {
                    Code = ApiCode.InternalError,
                    Message = ex.Message
                };
            }
        }
    }
}